import { Row, Col, Card, DatePicker, Button } from 'antd';
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import StatisticsCard from '@/components/StatisticsCard/Index';
import { Area, Line, DualAxes } from '@ant-design/charts';
import * as echarts from 'echarts';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { getShopBoardData, getShopOrderData } from '@/services/shop/api';
import {
  currentDate,
  formatDate,
  formatMoney,
  getDateValue,
  MsgType,
  showMsg,
  subtractDays,
} from '@/utils/utils';
import { history } from 'umi';
import moment from 'moment';

const Index: React.FC = () => {
  // 图表数据
  const [data, setData] = useState([]);

  const [transformData, setTransformData] = useState([]);

  // 店铺看板数据
  const [boardData, setBoardData] = useState<any>({});
  // 店铺订单数据
  const [shopOrderData, setShopOrderData] = useState<any>({});

  const [startDate, setStartDate] = useState<string>(
    formatDate(subtractDays(7).format('YYYY-MM-DD'), 'YYYY-MM-DD'),
  );
  const [endDate, setEndDate] = useState<string>(
    formatDate(currentDate().format('YYYY-MM-DD'), 'YYYY-MM-DD'),
  );

  const [dateStart] = useState(subtractDays(7));
  const [dateEnd] = useState(currentDate());

  let myChart;
  const [dateList, setDateList] = useState([]);
  const [mChart, setMChart] = useState(null);

  // const colorList = ['#8fcde5', '#768dd1', '#fbd379', '#f18585', '#a7d691', '#62b58e'];
  const colorList = ['#4C9DBE', '#4C7CBE', '#B1E181', '#70C67C', '#E68E7A', '#E6687A'];

  const fetchBoardData = async () => {
    try {
      const data = await getShopBoardData();
      setBoardData(data);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  };

  const fetchShopOrderData = async (params: any) => {
    try {
      const data = await getShopOrderData(params);
      setShopOrderData(data);
      handleChartsData(data.record_list);
    } catch (error) {
      console.log('error', error);
      showMsg(error?.data?.errmsg);
    }
  };

  const handleChartsData = (list: any[]) => {
    const dates = [],
      ary = [];
    list.map((item) => {
      dates.push(item.createDate);
      ary.push(item);
    });
    setDateList(dates);
    setData(ary);
  };

  const onSearch = () => {
    if (startDate && endDate) {
      if (getDateValue(moment(endDate)) < getDateValue(moment(startDate))) {
        showMsg('结束时间不能早于开始时间', MsgType.INFO);
        return;
      }
      const diff = moment(endDate).diff(startDate, 'days');

      const maxEnd = moment(startDate).add(90, 'days').format('YYYY-MM-DD');
      if (diff > 90) {
        showMsg(`最多查询90天范围的数据，结束日期可以选到【${maxEnd}】`, MsgType.INFO);
        return;
      }
    }

    fetchShopOrderData({
      begin_date: formatDate(startDate, 'YYYYMMDD'),
      end_date: formatDate(endDate, 'YYYYMMDD'),
    });
  };

  const navigateTo = (url: string, params: any) => {
    history.push({
      pathname: url,
      query: {
        ...params,
      },
    });
  };

  useEffect(() => {
    setTimeout(() => {
      myChart = echarts.init(document.getElementById('myChart'));
      setMChart(myChart);
    }, 500);
    fetchBoardData();
    onSearch();
  }, []);

  if (mChart) {
    mChart.setOption({
      animation: false,
      // color: ['#4EA8EC', '#17C295', '#83C2F1', '#F579A5', '#FFBC3A', '#D2691E'],
      color: colorList,
      grid: {
        left: '55',
        right: '55',
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
      },
      legend: {
        itemHeight: 9,
        itemWidth: 9,
        right: '5%',
        orient: 'horizontal',
        selectedMode: false,
        data: ['销售数量', '销售金额'],
        textStyle: {
          fontSize: 11,
        },
      },
      xAxis: {
        type: 'category',
        data: dateList,
      },
      yAxis: [
        {
          type: 'value',
          name: '数量',
          min: 0,
          max:
            data.length > 0 ? data.map((item) => item.total).sort((n1, n2) => n2 - n1)[0] : 10000,
          axisLabel: {
            formatter: '{value}单',
          },
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#4EA8EC',
            },
          },
        },
        {
          type: 'value',
          name: '金额',
          min: 0,
          max:
            data.length > 0
              ? data.map((item) => item.totalPrice).sort((n1, n2) => n2 - n1)[0]
              : 10000,
          axisLabel: {
            formatter: '￥{value}',
          },
          axisLine: {
            show: true,
            lineStyle: {
              // color: '#17C295',
            },
          },
        },
      ],
      dataZoom: [
        {
          type: 'slider',
          showDataShadow: false,
          start: 0,
          end: parseInt((7 * 100) / dateList.length),
          minValueSpan: 7,
          maxValueSpan: 7,
        },
        {
          type: 'inside',
          start: 0,
          end: parseInt((7 * 100) / dateList.length),
          minValueSpan: 7,
          maxValueSpan: 7,
        },
      ],
      series: [
        {
          name: '订单总数',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 0,
          data: data.map((item) => item.total),
        },
        {
          name: '订单总额',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 1,
          data: data.map((item) => item.totalPrice),
        },
        {
          name: '付款总数',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 1,
          data: data.map((item) => item.totalPayNum),
        },
        {
          name: '付款总额',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 1,
          data: data.map((item) => item.totalPayPrice),
        },
        {
          name: '退款总数',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 1,
          data: data.map((item) => item.totalRefundNum),
        },
        {
          name: '退款总额',
          type: 'line',
          barWidth: 35,
          yAxisIndex: 1,
          data: data.map((item) => item.totalRefundPrice),
        },
      ],
    });
  }

  // console.log('data', data)
  // console.log('myChart', myChart)
  // console.log('mChart', mChart)

  return (
    <PageContainer extra={[<BreadcrumbDept />]} breadcrumb={{}}>
      <div className="board-container">
        <div
          style={{
            marginBottom: 20,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <StatisticsCard
            iconType="database"
            title="今日订单总数"
            number={boardData.todayOrderNum}
          />
          <StatisticsCard title="今日销售总额" number={formatMoney(boardData.todayOrderPrice)} />
          <StatisticsCard title="昨日销售总额" number={formatMoney(boardData.yeOrderPrice)} />
          <StatisticsCard
            style={{ marginRight: 0 }}
            title="近7日销售总额"
            number={formatMoney(boardData.dayOrderPrice)}
          />
        </div>

        <Card title="待处理事务" style={{ marginBottom: 15 }}>
          <div className="card-inner">
            <div className="card-content">
              <div className="block-card">
                <div className="block-card-content">
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/order', { order_status: 'T' });
                    }}
                  >
                    <span>待付款订单</span>
                    <span className="danger">({boardData.waitPayOrderNum})</span>
                  </div>
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/order', { order_status: 'P' });
                    }}
                  >
                    <span>待发货订单</span>
                    <span className="danger">({boardData.waitSendOrderNum})</span>
                  </div>
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/order', { order_status: 'S' });
                    }}
                  >
                    <span>已发货订单</span>
                    <span className="danger">({boardData.sendOrderNum})</span>
                  </div>
                </div>
              </div>
              <div className="block-card">
                <div className="block-card-content">
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/after-sale', { way: '2', apply_status: 'U' });
                    }}
                  >
                    <span>待处理退款订单</span>
                    <span className="danger">({boardData.waitRefundNum})</span>
                  </div>
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/after-sale', { way: '1', apply_status: 'U' });
                    }}
                  >
                    <span>待处理退货订单</span>
                    <span className="danger">({boardData.waitRefundGoodsNum})</span>
                  </div>
                </div>
              </div>
              <div className="block-card">
                <div className="block-card-content">
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/evaluate', {});
                    }}
                  >
                    <span>待审核评价</span>
                    <span className="danger">({boardData.waitExamNum})</span>
                  </div>
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/consulting', {});
                    }}
                  >
                    <span>待处理咨询信息</span>
                    <span className="danger">({boardData.waitConsultNum})</span>
                  </div>
                  <div
                    className="block-card-item"
                    onClick={() => {
                      navigateTo('/shop/complaint', {});
                    }}
                  >
                    <span>待处理投诉信息</span>
                    <span className="danger">({boardData.waitStateNum})</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>

        <Row gutter={16}>
          <Col span={11}>
            <Card title="商品总览" style={{ marginBottom: 15 }}>
              <div className="card-inner goods-overview">
                <div className="card-content">
                  <div className="block-card">
                    <div className="block-card-content">
                      <div
                        style={{ flexDirection: 'column' }}
                        className="block-card-item"
                        onClick={() => {
                          navigateTo('/shop/goods', { goods_status: 'O' });
                        }}
                      >
                        <span className="highlight">{boardData.onlineGoodsNum}</span>
                        <span>已上架</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column' }}
                        className="block-card-item"
                        onClick={() => {
                          navigateTo('/shop/goods', { goods_status: 'D' });
                        }}
                      >
                        <span className="highlight">{boardData.downGoodsNum}</span>
                        <span>已下架</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column' }}
                        className="block-card-item"
                        onClick={() => {
                          navigateTo('/shop/goods', { flag: '1' });
                        }}
                      >
                        <span className="highlight">{boardData.warnGoodsNum}</span>
                        <span>库存紧张</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column' }}
                        className="block-card-item"
                        onClick={() => {
                          navigateTo('/shop/goods', {});
                        }}
                      >
                        <span className="highlight">{boardData.totalGodosNum}</span>
                        <span>全部商品</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
          <Col span={2} />
          <Col span={11}>
            <Card title="客户总览" style={{ marginBottom: 15 }}>
              <div className="card-inner goods-overview">
                <div className="card-content">
                  <div className="block-card">
                    <div className="block-card-content">
                      <div
                        style={{ flexDirection: 'column', cursor: 'text' }}
                        className="block-card-item"
                      >
                        <span className="highlight">{boardData.todayUserNum}</span>
                        <span>今日新增</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column', cursor: 'text' }}
                        className="block-card-item"
                      >
                        <span className="highlight">{boardData.yeUserNum}</span>
                        <span>昨日新增</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column', cursor: 'text' }}
                        className="block-card-item"
                      >
                        <span className="highlight">{boardData.monthUserNum}</span>
                        <span>本月新增</span>
                      </div>
                      <div
                        style={{ flexDirection: 'column', cursor: 'text' }}
                        className="block-card-item"
                      >
                        <span className="highlight">{boardData.totalUserNum}</span>
                        <span>总客户数</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>

        <Card title="订单统计" style={{ marginBottom: 15 }}>
          <div className="card-inner">
            <div className="card-side">
              <div className="side-item">
                <div className="title" style={{ color: colorList[0] }}>周期订单总数</div>
                <div className="num">{shopOrderData.totalOrderNum}</div>
              </div>
              <div className="side-item">
                <div className="title" style={{ color: colorList[1] }}>周期订单总额</div>
                <div className="num">{formatMoney(shopOrderData.totalOrderPrice)}</div>
              </div>
              <div className="side-item">
                <div className="title" style={{ color: colorList[2] }}>周期付款总数</div>
                <div className="num">{formatMoney(shopOrderData.totalPayNum)}</div>
              </div>
              <div className="side-item">
                <div className="title" style={{ color: colorList[3] }}>周期付款总额</div>
                <div className="num">{formatMoney(shopOrderData.totalPayPrice)}</div>
              </div>
              <div className="side-item">
                <div className="title" style={{ color: colorList[4] }}>周期退款总数</div>
                <div className="num">{formatMoney(shopOrderData.totalRefundNum)}</div>
              </div>
              <div className="side-item">
                <div className="title" style={{ color: colorList[5] }}>周期退款总额</div>
                <div className="num">{formatMoney(shopOrderData.totalRefundPrice)}</div>
              </div>
            </div>
            <div className="card-content">
              <div className="area-wrap">
                <div className="date">
                  <DatePicker
                    allowClear={false}
                    defaultValue={dateStart}
                    onChange={(date, dateString) => {
                      setStartDate(dateString);
                    }}
                    name="startDate"
                    style={{ width: 150 }}
                  />
                  <span style={{ padding: '0 10px' }}>-</span>
                  <DatePicker
                    allowClear={false}
                    onChange={(date, dateString) => {
                      setEndDate(dateString);
                    }}
                    // disabledDate={current => {
                    //   const tooLate = startDate && current.diff(startDate, 'days') > 90;
                    //   const tooEarly = current && current.diff(current, 'days') > 90;
                    //   return tooEarly || tooLate;
                    // }}
                    name="endDate"
                    defaultValue={dateEnd}
                    style={{ width: 150 }}
                  />
                  <Button onClick={onSearch} style={{ marginLeft: 10 }} type="primary">
                    查询
                  </Button>
                </div>
                {/* <DualAxes className="area" {...config} /> */}
                <div id="myChart" style={{ width: '100%', margin: '0 auto', height: '100%', minHeight: 300 }} />
              </div>
            </div>
          </div>
        </Card>
      </div>
    </PageContainer>
  );
};
export default Index;
